package com.dominator.utils.ocr;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dominator.enums.ReqEnums;
import com.dominator.utils.api.ApiUtils;
import com.dominator.utils.exception.ApiException;
import com.dominator.utils.pay.WeixinSign;
import com.dominator.utils.qiniu.QiniuUploadFile;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 合合ocr工具
 */
@Slf4j
public class IntsigUtils {


    private  static  String  userName="changjiangzhengquan";

    private  static  String  password="RF6lY4Otgka0";



    /**
     * 扫描图片
     * @param multipartFile
     * @return
     */
    public static String ocrPicture(MultipartFile multipartFile) {
        CommonsMultipartFile cFile = (CommonsMultipartFile) multipartFile;
        DiskFileItem fileItem = (DiskFileItem) cFile.getFileItem();
        InputStream inputStream = null;
        try {
            inputStream = fileItem.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ocrPicture(inputStream);
    }


    /**
     * 扫描图片
     * @param bytes
     * @return
     */
    public static String ocrPicture(byte[] bytes) {
        InputStream inputStream = new ByteArrayInputStream(bytes);
        return ocrPicture(inputStream);
    }

    /**
     * 扫描微信图片,传七牛
     * @param mediaId
     * @return
     */
    public static String ocrPictureByWeixin(String mediaId) {
        byte[] bytes = WeixinSign.downloadMedia(mediaId);
       String url=QiniuUploadFile.upload(bytes,"jpg","ocrticket");
       log.info(url);
       return url;
    }

    /**
     * 扫描图片
     * @param imgUrl
     * @return
     */
    public static String ocrPictureByUrl(String imgUrl) {
        URL url = null;
        HttpURLConnection httpUrl = null;
        BufferedInputStream bis = null;
        try {
            url= new URL(imgUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());

        }catch (Exception e){

        }
        return ocrPicture(bis);
    }



    /**
     * 扫描图片
     * @param inputStream
     * @return
     */
    public static String ocrPicture(InputStream inputStream) {
        String retString = null;
        String urlString = "http://imgs-sandbox.intsig.net/icr/recognize_document?user="+userName+"&password="+password;
        try {
            URL url = new URL(urlString);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setRequestMethod("POST");
            con.setRequestProperty("Charset", "utf-8");
            OutputStream out = con.getOutputStream();
            byte[] data = new byte[2048];
            int len = 0;
            int sum = 0;
            while ((len = inputStream.read(data)) != -1) {
                out.write(data, 0, len);
                sum = len + sum;
            }
            System.out.println("upload size=" + sum);
            out.flush();
            inputStream.close();
            out.close();
            int code = con.getResponseCode();
            System.out.println("code=" + code + " url=" + url);
            if (code == 200) {
                InputStreamReader inputStreamReader = new InputStreamReader(con.getInputStream(), "utf-8");
                BufferedReader br = new BufferedReader(inputStreamReader);
                String line = "";
                StringBuffer sbBuffer = new StringBuffer();
                while (null != (line = br.readLine())) {
                    sbBuffer.append(line);
                }
                System.out.println("result =" + sbBuffer.toString());
                br.close();
                inputStreamReader.close();
                retString =sbBuffer.toString();
            } else {
                retString = code + "服务器http返回错误";
            }
            con.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
            throw new ApiException(ReqEnums.OCR_ERROR);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ApiException(ReqEnums.OCR_ERROR);
        }
        return retString;
    }

    /**
     * 判断ocr是否识别到手机号
     * @param str
     * @return
     */
    public static String  checkResIncludeMobile(String str){
        log.info("ocr识别内容："+str);
        JSONObject json=new JSONObject();
        String resPhoneNum="";
        try {
            json=JSON.parseObject(str);
            JSONArray linesTextArray = json.getJSONArray("linesText");
            for (Object object:linesTextArray){
                boolean res=ApiUtils.isIncludeMobile(object.toString());
                if (res){
                    resPhoneNum=object.toString();
                    break;
                }
            }
        }catch (Exception e){
            throw new ApiException(ReqEnums.IDENTIFICATION_IS_FAILURE);
        }
        return resPhoneNum;
    }






}